import { errorCode } from '@constant/index'
import { message } from 'ant-design-vue'
import axios, { type AxiosRequestConfig } from 'axios'
import qs from 'qs'

const service = axios.create({
  baseURL: VITE_BASE_API_URL,
  paramsSerializer: (params) => qs.stringify(params, { encode: true })
})

service.interceptors.response.use(
  (response) => {
    const code = response.data.code
    // console.log(response.data);
    const msg =
      errorCode[code as unknown as keyof typeof errorCode] ||
      response.data.msg ||
      errorCode['default']

    if (code === 500) {
      message.error(msg)
      return Promise.reject(new Error(msg))
    }
    if (!response.data.data) {
      response.data.data = {}
    }
    return response.data
  },
  (err) => {
    if (err.response?.data?.message) {
      message.error(err.response.data.message)
    }

    return Promise.reject(err.message)
  }
)

export function request<T>(config: AxiosRequestConfig): Promise<T> {
  return service(config)
}
